package com.atguigu.tingshu.common.login;


import com.alibaba.nacos.plugin.auth.constant.Constants;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class GuiGuLoginAspect {

    @Autowired
    RedisTemplate redisTemplate;




    //实现登录校验
    @Around("@annotation(guiGuLogin)")
    public Object loginAround(ProceedingJoinPoint joinPoint,GuiGuLogin guiGuLogin ) throws Throwable{
        //1.获取token
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("token");
        //2.判断token是否为空，不为空则根据token查询登录状态   redis
        UserInfoVo userInfoVo = null;


        if(StringUtils.isNotBlank(token)) {
            //3.查询redis中的登录状态
             userInfoVo =(UserInfoVo)redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);

        }

        //4.判断登录状态是否为空，并且是否必须登录 如果是 则抛出异常 guiGuLogin
        if (userInfoVo==null&& guiGuLogin.required()){
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        //5.放入threadlocal
        if (userInfoVo!=null){
            //存入线程变量
            AuthContextHolder.setUserId(userInfoVo.getId());
            AuthContextHolder.setUsername(userInfoVo.getNickname());
        }
        //6.执行业务操作
        Object proceed = joinPoint.proceed(joinPoint.getArgs());

        //7.释放threadlocal中的缓存

        AuthContextHolder.removeUserId();
        AuthContextHolder.removeUsername();

        return proceed;
    }




}
